var jweixin = require('../components/jweixin-module/index.js');
var request = require('./http.js')

export default {
	//判断是否在微信中  
	isWechat: function() {
		var ua = window.navigator.userAgent.toLowerCase();
		if (ua.match(/micromessenger/i) == 'micromessenger') {
			// console.log('是微信客户端')
			return true;
		} else {
			// console.log('不是微信客户端')
			return false;
		}
	},
	//初始化sdk配置  
	initJssdkShare: function(callback, url) {
		var post_data = {
			url: url
		}
		
		request({
			url: "Customizedapi/Common/get_wachat_info",
			hideLoading: true,
			data: post_data,
			success: res => {
				// console.log(res)
				let result = res.data

				jweixin.config({
					// debug: true,
					debug: false,
					appId: result.appId,
					timestamp: result.timestamp,
					nonceStr: result.nonceStr,
					signature: result.signature,
					jsApiList: [
						'checkJsApi',
						'onMenuShareTimeline',
						'onMenuShareAppMessage',
						'scanQRCode'
					]
				});
				//配置完成后，再执行分享等功能  
				if (callback) {
					callback(result);
				}
			}
		})
	},
	//在需要自定义分享的页面中调用  
	share: function(data, url) {
		url = url ? url : window.location.href;

		// console.log("url:" + url)
		// if (!this.isWechat()) {
		// 	return;
		// }
		//每次都需要重新初始化配置，才可以进行分享  
		this.initJssdkShare(function(signData) {
			jweixin.ready(function() {
				var shareData = {
					title: data && data.title ? data.title : signData.site_name,
					desc: data && data.desc ? data.desc : signData.site_description,
					link: url,
					imgUrl: data && data.img ? data.img : signData.site_logo,
					success: function(res) {
						// 分享后的一些操作,比如分享统计等等
					},
					cancel: function(res) {}
				};
				//分享给朋友接口  
				jweixin.onMenuShareAppMessage(shareData);
				//分享到朋友圈接口  
				jweixin.onMenuShareTimeline(shareData);
			});
		}, url);
	},

	//在需要自定义扫码的页面中调用
	search: function() {
		var url = window.location.href;
		// if (!this.isWechat()) {
		// 	return;
		// }
		//每次都需要重新初始化配置，才可以进行分享  
		this.initJssdkShare(function() {
			jweixin.ready(function() {
				// /微信扫一扫接口  
				jweixin.scanQRCode({
					needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
					scanType: ["qrCode", "barCode"], // 
					success: (res) => {
						var regex = /user_ziti=[0-9]*?/;
						var str = res.resultStr;
						if (regex.test(str)) {
							var arr = str.split("=");
							uni.navigateTo({
								url: '/pages/order/list?wait_zt=1&user_id=' + arr[1],
							})
							return false;
						}
					}
				});
			});
		}, url);
	}
}
